package com.deepglint.state;

import com.deepglint.beans.SensorReading;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @author mj
 * @version 1.0
 * @date 2021-11-22 22:52
 */
public class StateTest_keyedStateApplicationCase {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.setStreamTimeCharacteristic(); // 1.12开始，默认的就是eventTime
        env.getConfig().setAutoWatermarkInterval(200);// 设置周期性的waterMark的周期时间

        DataStream<String> streamSource = env.socketTextStream("192.168.150.128", 7777);

        DataStream<SensorReading> dataStream = streamSource.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], split[1], new Long(split[2]), new Double(split[3]));
        });

        SingleOutputStreamOperator<Tuple3<String, Double, Double>> mapStream = dataStream.keyBy("id").flatMap(new MyTempWaring(10.3));

        mapStream.print();

        env.execute();
    }

    // 与上一次的温度相比，温度差超过10度，则报警
    static class MyTempWaring extends RichFlatMapFunction<SensorReading, Tuple3<String, Double, Double>> {

        // 私有属性，温度跳变阈值
        private Double threshold;

        public MyTempWaring(Double threshold) {
            this.threshold = threshold;
        }

        // 定义状态，保存上一次的值
        private ValueState<Double> lastTemp;

        @Override
        public void open(Configuration parameters) throws Exception {
            lastTemp = getRuntimeContext().getState(new ValueStateDescriptor<Double>("last_temp", Double.class));
        }

        @Override
        public void flatMap(SensorReading value, Collector<Tuple3<String, Double, Double>> out) throws Exception {
            // 如果状态不为null，就判断两次的温度的差值
            if (lastTemp.value() != null) {
                double diff = Math.abs(value.getTemperature() - lastTemp.value());
                System.out.println(diff);
                if (diff > threshold) {
                    out.collect(new Tuple3<String, Double, Double>(value.getId(), lastTemp.value(), value.getTemperature()));
                }
            }

            lastTemp.update(value.getTemperature());
        }

        @Override
        public void close() throws Exception {
            lastTemp.clear();
        }
    }
}
